<!-- 
 * 省市区选择器
 * @作者：陈万照
 * @公司：山东标梵互动信息技术有限公司
 * @官网：http://biaofun.com/
 * @微信：C207668802
 * @QQ：207668802
 * @邮箱：cwz@biaofun.com || 207668802@qq.com
 * @版本：v1.0.8
 -->
<template>
	<view class="region">
		<!-- #ifdef MP-WEIXIN -->
		<picker mode="multiSelector" :range="range" range-key="name" @change="change" @columnchange="columnchange" :value="value" :disabled="disabled">
			<view class="content" :class="{ placeholder: !regionStr }">
				<text class="ellipsis-1">{{ regionStr ? regionStr : placeholder }}</text>
			</view>
		</picker>
		<!-- #endif -->
		<!-- #ifdef MP-ALIPAY -->
    <text class="ellipsis-1">{{ regionStr ? regionStr : placeholder }}</text>

    <cover-view style=" height: 90vh;
    background-color: white;
    z-index: 1000;
    display: block;
    position: relative;">
      <picker-view  :indicator-style="indicatorStyle" :value="value1" @change="bindChange" class="picker-view">
        <picker-view-column>
          <view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
        </picker-view-column>
        <picker-view-column>
          <view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
        </picker-view-column>
        <picker-view-column>
          <view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
        </picker-view-column>
      </picker-view>
      </cover-view>

		<!-- #endif -->
  
	</view>
</template>

<script>
let  regionData = [];
export default {
	/**
	 * 数据
	 */
	props: {
		// 是否禁用
		disabled: {
			type: Boolean,
			default: false
		},

		// placeholder
		placeholder: {
			type: String,
			default: '请选择省/市/区'
		},

		// 默认值
		defaultValue: {
			type: Array,
			default() {
				return null;
			}
		}
	},

	/**
	 * 数据
	 */
	data() {
    const date = new Date()
    const years = []
    const year = date.getFullYear()
    const months = []
    const month = date.getMonth() + 1
    const days = []
    const day = date.getDate()
    for (let i = 1990; i <= date.getFullYear(); i++) {
      years.push(i)
    }
    for (let i = 1; i <= 12; i++) {
      months.push(i)
    }
    for (let i = 1; i <= 31; i++) {
      days.push(i)
    }
		return {
      title: 'picker-view',
      years,
      year,
      months,
      month,
      days,
      day,
      value1: [9999, month - 1, day - 1],
      visible: true,
      indicatorStyle: `height: 50px;`,
			range: [[], [], []], // 省/市/区
			value: [0, 0, 0], // value 的值表示选择了 range 中的第几个（下标从 0 开始）,默认为 [0, 0, 0]，即 range 为 ['第一个省', '第一个省的第一个市', '第一个省的第一个市的第一个区']
			regionStr: '' // 选中的省市区字符串
		};
	},

	/**
	 * 监听数据
	 */

	watch: {
		// 默认值
		defaultValue() {
			// 设置/更新省市区数据
			this.defaultValue ? this.setDefaultValue() : this.setRange();
		}
	},

 async created(){







  },
	/**
	 * 组件初次加载完成
	 */
	async mounted() {
    regionData = await uni.getStorageSync("region")
    console.log("rrrrr",regionData)
    if(regionData!=undefined &&regionData!=null &&regionData!=''){
      this.defaultValue ? this.setDefaultValue() : this.setRange();
      return
    }
    console.log("wwwwwwwwwwwwwwwwwwwwwwwwwwww")
    await this.getRegion();
		// 设置/更新省市区数据
	},

	/**
	 * 函数
	 */
	methods: {
    bindChange: function (e) {
      console.log("ee",e)
      const val = e.detail.value
      this.year = this.years[val[0]]
      this.month = this.months[val[1]]
      this.day = this.days[val[2]]
    },
    /**
     * 动态获取行政区域信息
     */
     async getRegion(){
      return new Promise(resolve => {
        this.$api.ajax({
          url: "https://tangbantian.oss-cn-beijing.aliyuncs.com/region/region.json",
          method: "get",
          success: (res) => {
            regionData = res.data
            console.log("region",regionData)
            for(let item of regionData){
              let {children}  = item
              for(let item1 of children){
                //console.log("sss",item1.children)
                if(item1.children!=null && item1.children.length>0){
                  if(item1.children[0].id == -999){
                    continue
                  }
                }
                item1.children.unshift({
                  id: -999,
                  level: 3,
                  name: "全部地区",
                  pid: item1.id
                })
              }
            }
            uni.setStorageSync("region",regionData)
            this.defaultValue ? this.setDefaultValue() : this.setRange();
            resolve();
          }
        });
      })


    },
		/**
		 * 设置/更新省市区数据
		 */
		setRange() {
			// 省市区数据
			let range = [[], [], []];

			// 省
			regionData.forEach(el => {
				range[0].push({
					id: el.id,
					level: el.level,
					name: el.name,
					pid: el.pid
				});
			});

			// 市
			regionData[this.value[0]].children.forEach((el,index) => {

				range[1].push({
					id: el.id,
					level: el.level,
					name: el.name,
					pid: el.pid
				});
			});

			// 区
			regionData[this.value[0]].children[this.value[1]].children.forEach((el,index) => {
				range[2].push({
					id: el.id,
					level: el.level,
					name: el.name,
					pid: el.pid
				});
			});

			// 更新省市区数据
			this.range = range;
		},

		/**
		 * 设置默认值
		 */
		setDefaultValue() {
      if(regionData.length ==0) return;
			// 查找省
			let provinceIndex = regionData.findIndex(el => {
				return el.name == this.defaultValue[0];
			});
			if(provinceIndex < 0) provinceIndex = 0;
			// 查找市
			let cityIndex = regionData[provinceIndex].children.findIndex(el => {
				return el.name == this.defaultValue[1];
			});
			if(cityIndex < 0) cityIndex = 0;

			// 查找区
			let areaIndex = regionData[provinceIndex].children[cityIndex].children.findIndex(el => {
				return el.name == this.defaultValue[2];
			});

			if(areaIndex < 0) {
			  if(areaIndex !=-999){
			    areaIndex = 0
        }
      }

			// 更新 value 的值
			this.value = [provinceIndex, cityIndex, areaIndex];

			// 设置/更新省市区数据
			this.setRange();

			// 更新选中的省市区字符串
			this.regionStr =
				regionData[provinceIndex].name + '·' + regionData[provinceIndex].children[cityIndex].name + '·' + regionData[provinceIndex].children[cityIndex].children[areaIndex].name;
		},

		/**
		 * 某一列的值改变时触发
		 * @param {Number} event.detail.column 表示改变了第几列（下标从0开始）
		 * @param {Number} event.detail.value 表示变更值的下标
		 */
		columnchange(event) {
			// 改变的是省
			if (event.detail.column == 0) {
				this.value = [event.detail.value, 0, 0];
			}
			// 改变的是市
			if (event.detail.column == 1) {
				this.value.splice(1, 1, event.detail.value);
				this.value.splice(2, 1, 0);
			}
			// 改变的是区
			if (event.detail.column == 2) {
				this.value.splice(2, 1, event.detail.value);
			}

			// 设置/更新省市区数据
			this.setRange();
		},

		/**
		 * 确认选择
		 */
		change(event) {
      console.log("sssssss")
			// 更新选中的省市区字符串
			this.regionStr = this.range[0][this.value[0]].name + '·' + this.range[1][this.value[1]].name + '·' + this.range[2][this.value[2]].name;
      console.log(this.regionStr)

			// 传递事件
			this.$emit('change', [this.range[0][this.value[0]], this.range[1][this.value[1]], this.range[2][this.value[2]]]);
		}
	}
};
</script>

<style lang="scss" scoped>
.ellipsis-1 {
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 1;
	overflow: hidden;
  margin-left:0.7rem
}

.content {
	text-align: left;
}

.placeholder {
	color: #949596;
}
.picker-view {
  width: 750rpx;
  height: 600rpx;
  margin-top: 200rpx;
}
.item {
  height: 50px;
  align-items: center;
  justify-content: center;
  text-align: center;
}
</style>
